<template>
  <a-select
    :allowClear="true"
    :placeholder="placeholder"
    v-model:value="selectedEditionIndex"
    @change="selectChange($event)"
  >
    <a-select-option v-for="(item, index) of editions" :key="index" :value="index">
      {{ item.displayText }}
    </a-select-option>
  </a-select>
</template>

<script lang="ts">
  import { AppComponentBase } from '/@/shared/component-base';
  import {
    EditionServiceProxy,
    SubscribableEditionComboboxItemDto,
  } from '/@/shared/service-proxies';
  import { defineComponent } from 'vue';
  export default defineComponent({
    name: 'EditionCombo',
    mixins: [AppComponentBase],
    props: {
      placeholder: {
        type: String, // 实际传过来的类型
      },
      selectedEdition: {
        type: String, // 实际传过来的类型
      },
      editionId: {
        type: String, // 实际传过来的类型
      },
    },
    emits: ['selectedEditionChange'],
    data() {
      return {
        editionService: new EditionServiceProxy(), // 版本信息api
        editions: new Array<SubscribableEditionComboboxItemDto>(), // 所有的版本信息
        editionIdVal: this.editionId, // 版本id
        selectedEditionVal: this.selectedEdition,
        selectedEditionIndex: 0, // 选中版本信息的索引
      };
    },
    watch: {
      selectedEdition(val) {
        this.selectedEditionVal = val;
        this.autoSelect();
      },
      editionId(val) {
        this.editionIdVal = val;
        this.autoSelect();
      },
    },
    mounted() {
      this.editionService.getEditionComboboxItems(0, true, false).then((editions) => {
        this.editions = editions;
        this.autoSelect();
      });
    },
    methods: {
      autoSelect() {
        if (!this.editions) {
          return;
        }

        let callSelectChange = false;

        if (this.selectedEditionVal) {
          this.selectedEditionIndex = this.editions.findIndex((item) => {
            return item.value === this.selectedEditionVal?.toString();
          });

          callSelectChange = true;
        } else if (this.editionIdVal) {
          this.selectedEditionIndex = this.editions.findIndex((item) => {
            return item.value === this.editionIdVal?.toString();
          });

          callSelectChange = true;
        }

        if (callSelectChange) {
          this.selectChange(this.editions[this.selectedEditionIndex]);
        }
      },
      selectChange(e) {
        if (typeof e === 'object') {
          this.$emit('selectedEditionChange', e);
          return;
        }

        this.selectedEditionIndex = e;

        if (e >= 0) {
          this.$emit('selectedEditionChange', this.editions[this.selectedEditionIndex]);
          return;
        }

        this.$emit('selectedEditionChange', null);
      },
    },
  });
</script>

<style lang="less" scoped>
  .ant-select {
    width: 100%;
  }
</style>
